package com.tools;

import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;

public class MysqlUtil {
	private String dataSourceName;
	private DataSource ds;

	public MysqlUtil() {

	}

	public MysqlUtil(String dataSourceName) {
		this.dataSourceName = dataSourceName;
	}

	public void init() {
		try {
			Context initContext = new InitialContext();
			this.ds = (DataSource) initContext.lookup(dataSourceName);
			initContext.close();
		} catch (NamingException e) {
			e.printStackTrace();
		}
	}

	public int update(String sql, String[] params) {
		int result = 0;
		QueryRunner qr = new QueryRunner(ds);
		try {
			result = qr.update(sql, params);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}

	public Object query(String sql, String[] params, ResultSetHandler rsh) {
		QueryRunner qr = new QueryRunner(ds);
		Object results = null;
		try {
			results = qr.query(sql, params, rsh);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return results;
	}

	public void setDataSourceName(String dataSourceName) {
		this.dataSourceName = dataSourceName;
	}

	public void setDs(DataSource ds) {
		this.ds = ds;
	}
}
